<template>
    <div class="TitleTop_div" >
       <!-- <slot name="components_title">  </slot>-->
        <div slot="components_title">
            <a-row class="homework_title_row">
                <a-col :span="8" class="homework_title_col" id="homework_title_col1">
                    <div id="nickname">
                        <strong>{{username}}</strong>
                    </div>
                    <div id="username">
                        {{$store.state.workModeName}}
                    </div>
                </a-col>
                <a-col :span="12" class="homework_title" id="homework_title_col2">
                    <div id="homework_tip">
                        您已上线，请注意安全
                    </div>
                    <div id="homework_time">
                        <!--{{workTime}}-->
                        作业时长：{{$store.state.workTime}}
                    </div>
                </a-col>
                <a-col :span="4" class="homework_title"  id="homework_title_col3" @click="jumpRouter()" >
                    <div id="homework_warn_ico">
                        <a-icon type="warning" style="font-size: 8vw" />
                        <div class="top_circle" v-if="this.$store.state.countWarningNumber!==''">{{this.$store.state.countWarningNumber}}</div>
                    </div>
                    <div id="homework_warn_text">
                        报警
                    </div>
                </a-col>
            </a-row>
        </div>
    </div>
</template>
<style>
    .TitleTop_div{
        width: 100vw;
        height: 16.25vw;
        line-height:16.25vw;
        background-image: url("./../assets/drawable-mdpi/user_bg.png");
        text-align: center;
        background-size:100%;
        margin: 0;
        padding: 0;
        font-family: PingFangSC-Semibold;
        color: #FFFFFF;

    }
    .homework_title_col{
        height: 16.25vw;
        color: #ffffff;
    }
    .homework_title{
        height: 16.25vw;
        color: #ffffff;
    }
    #homework_title_col1{
        padding-left: 2vw;
    }
    #nickname{
        height: 9.546vw;
        line-height: 11.546vw;
        font-size: 5vw;
        text-align: center;

    }
    #username{
        height: 6.704vw;
        line-height: 5vw;
        font-size: 4vw;
    }
    #homework_tip{
        margin-top: 1vw;
        height: 8.546vw;
        line-height: 8.546vw;
        font-size: 4vw;
        text-align: left;
        padding-left: 3vw;
    }
    #homework_time{
        height: 6.704vw;
        line-height: 3.704vw;
        font-size: 4vw;
        text-align: left;
        padding-left: 3vw;
    }
    #homework_warn_ico{
        height: 9vw;
        line-height: 9vw;
        font-size: 4vw;
        padding-top: 2vw;
        position: relative;
    }
    #homework_warn_text{
        height: 6.25vw;
        line-height: 7vw;
        font-size: 4vw;
    }
    .top_circle{
        width:6vw;
        height: 6vw;
        line-height: 6vw;
        background: #FF3850 100% ;
        -moz-border-radius: 3vw;
        -webkit-border-radius: 3vw;
        border-radius:3vw;
        color: white;
        text-align: center;
        font-weight: normal;
        font-size: 5vw;
        position:absolute;
        right: 1.8vw;
        top: 1.2vw;
    }
</style>
<script>
    export default {
        name: "TitleTop",
        data() {
            return {
                msg: 'hello vue',
                workTime:"",
                timerTime:null,
                workModeName:localStorage.getItem("workModeName")?localStorage.getItem("workModeName"):localStorage.getItem("sid"),
                websocket: null,
                wsData:'',
                lock:false,
            }
        },
        created(){

        },
        destroyed: function() {
            //页面销毁时关闭长连接
           /* this.websocketclose();*/
            //关闭定时器
            clearInterval(this.timerTime);
            this.timerTime = null;
        },
        mounted(){
            //页面刚进入时开启长连接
            this.initWebSocket()
            this.beginWorkTime();
        },
        computed: {
            username () {
                return this.$store.state.username;
            },
            /*gis4_phone () {
                return this.$store.state.gis4_phone;
            },*/
        },
        methods:{
            beginWorkTime(){

                this.timerTime = setInterval(getTime,1000);
                    // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
                let me = this;
                /*window.setInterval(getTime, 1000);*/
                function getTime() {

                    //获取一个登录的时间
                    let loginTime =localStorage.getItem("gis4_time");
                    //获取一个现在的时间
                    let nowdate = new Date().getTime();
                    //获取时间差 把毫秒转换为秒
                    let diff = parseInt((nowdate - loginTime) / 1000);
                    let h = parseInt(diff / 3600);//获取还有小时
                    let m = parseInt(diff / 60 % 60);//获取还有分钟
                    let s = diff % 60;//获取多少秒数

                    //将时分秒转化为双位数
                    let h1 = setNum(h);
                    let m1 = setNum(m);
                    let s1 = setNum(s);

                    //输出时分秒
                    me.workTime = h1+":"+m1+":"+s1;
                    me.$store.commit("updateWorkTime",me.workTime);

                }
                //设置函数 把小于10的数字转换为两位数
                function setNum(num) {
                    if (num < 10) {
                        num = "0" + num;
                    }
                    return num;
                }
            },
            initWebSocket(){ //初始化weosocket
                let me = this ;
                let myImei = localStorage.getItem("gis4_imei");
                if(myImei===""){
                    myImei = "866719048888888";
                }

                //let host = "api.gis4.tdzcsoft.com:7000";
                let host = localStorage.getItem("apiHost");
                //const wsuri = "ws://api.gis4.tdzcsoft:7000/msg?gis4_imei=657578767656570";//ws地址

                let WebSocketConfig = {
                    imei: myImei,
                    url: 'ws://' + host + '/msg?gis4_imei={imei}',
                    heartBeat: {
                        last: new Date().getTime(),
                        over: 6000,
                    },
                    onOpen: function (ws, e) {
                        console.log("WebSocket连接成功");
                    },
                    onError: function (ws, e) {
                        console.log("WebSocket连接发生错误");
                    },
                    onClose: function (ws, e) {
                        console.log("WebSocket连接关闭");
                        /* if (confirm('WebSocket连接关闭， 是否刷新页面')) {
                             location.reload();
                         }*/
                    },

                    onMessage: function (ws, e) {
                        this.heartBeat.last = new Date().getTime();
                        me.wsData = e.data;
                        console.log("接收到服务端消息：" + me.wsData);
                        if(me.wsData ==="FloodsWarning"){
                            console.log("FloodsWarning");
                            me.$api.getFloodsWarning().then(function(response){
                                if(response.status === 200){
                                    if(typeof(navigator.notification)!=="undefined"){
                                        navigator.notification.beep(1);
                                    }

                                    let data = response.data.result.data;
                                    /*let message={};
                                    for(let i in data){
                                        /!*Vue.set(message, "msg"+i, data[i].message);*!/
                                        message["msg"+i] = data[i].message;
                                    }
                                    console.log(message);
                                    me.updateFloodsWarning(message);*/
                                    let temp = {};
                                    let end = [];
                                    for(let i = 0; i < data.length; i++){
                                        let a = data[i];
                                        if(!temp[a.workModeId]){
                                            end.push({
                                                workModeId: a.workModeId,
                                                workMode:a.workMode,
                                                data: [a]
                                            });
                                            temp[a.workModeId] = a;

                                        }else{
                                            for(let j = 0; j < end.length; j++){
                                                let b = end[j];
                                                if(b.workModeId === a.workModeId){
                                                    b.data.push(a);
                                                    break;
                                                }
                                            }

                                        }
                                    }//for end
                                    me.$store.commit("countWarningNumber",data.length);
                                    me.$store.commit("updateFloodsWarning",end);
                                }
                            }).catch(function(error){
                                console.log(error);
                            });
                        }else if(me.wsData ==="FloodsMessage"){
                            me.$api.getFloodsMessage().then(function(response){
                                //先以FloodsMessage做测试
                                if(response.status === 200){
                                    if(typeof(navigator.notification)!=="undefined"){
                                        navigator.notification.beep(1);
                                    }
                                    let data = response.data.result;
                                    let message={};
                                    for(let i in data){
                                        /*Vue.set(message, "msg"+i, data[i].message);*/
                                        message["msg"+i] = data[i];
                                    }
                                    /* me.updateFloodsMessage(message);*/
                                    me.$store.commit("updateFloodsMessage",message);
                                }
                            }).catch(function(error){
                                console.log(error);
                            });
                        }else{
                            console.log("getFlood else with TitleTop page");
                        }
                    },
                    reConnect: function (ws) {
                        if (ws.readyState !== WebSocket.OPEN) {
                            //1 1
                            return;
                        }
                        // console.log("socket 连接断开，正在尝试重新建立连接");
                        ws.send('ping');
                    },
                    auto: function (ws) {
                        let me = this;
                        setInterval(function () {
                            if ((new Date().getTime() - me.heartBeat.last) >= me.heartBeat.over) {
                                me.heartBeat.last = new Date().getTime();
                                me.reConnect(ws);
                            }
                        }, 1000);
                    },
                }//config结束

                me.websocket = new WebSocket(WebSocketConfig.url.replace('{imei}', WebSocketConfig.imei));
                me.websocket.onopen =  function (e) { WebSocketConfig.onOpen.call(WebSocketConfig, me.websocket, e); }
                me.websocket.onmessage = function (e) { WebSocketConfig.onMessage.call(WebSocketConfig, me.websocket, e); }
                me.websocket.onerror = function (e) { WebSocketConfig.onError.call(WebSocketConfig, me.websocket, e); }
                me.websocket.onclose = function (e) { WebSocketConfig.onClose.call(WebSocketConfig, me.websocket, e); }
                WebSocketConfig.auto.call(WebSocketConfig, me.websocket);

            },//该方法结束
            jumpRouter(){
                this.clickButton();
                this.$router.push('/warnInfo');
            },
        },


    }
</script>

